<?php
namespace zzcms\primary\controller;


class Category extends Base
{
    protected $model;

    protected function initialize()
    {
        parent::initialize();
        $this->model = new \zzcms\admin\model\Category();
    }

    /**
     * 分类信息
     * @return mixed
     */
    public function lists()
    {
        $module = isset($this->info['module']) ? $this->info['module'] : 0;
        $cate_cache = getCache('category');
        $lists = [];
        foreach ($cate_cache as $item) {
            if ($module > 0 && $module != $item['module']) {
                continue;
            }
            $url = $item['module'] == 1 ? '/pages/news/lists/lists?id=' . $item['id'] : '/pages/article/lists/lists?id=' . $item['id'];
            $data = [
                'id' => $item['id'],
                'catename' => $item['catename'],
                'thumb' => '/static/images/n_7.png',
                'url' => $url
            ];
            $lists[] = $data;
        }
        $lists = array_chunk($lists, 5);
        $this->array2json(['code' => 0, 'data' => $lists[0]]);
    }

    /**
     * 分类信息
     * @return mixed
     */
    public function index()
    {
        $lists = [];
        $lists[] = [
            'catename' => 'POS产品',
            'thumb' => '/static/images/n_7.png',
            'url' => '/pages/product/lists/lists'
        ];
        $lists[] = [
            'catename' => 'POS课堂',
            'thumb' => '/static/images/n_7.png',
            'url' => '/pages/article/lists/lists'
        ];
        $lists[] = [
            'catename' => '新闻资讯',
            'thumb' => '/static/images/n_7.png',
            'url' => '/pages/news/lists/lists'
        ];
        $this->array2json(['code' => 0, 'data' => $lists]);
    }

    public function catetree()
    {
        $areas = getCache('linkage');
        $trees = $this->getCateTree($areas, '', ['where' => ['keyid' => 1]]);
        file_put_contents(SITE_PATH . 'area.js', array2json($trees));
        $this->array2json(['code' => 0, 'data' => $trees]);
    }

    /**
     * 格式化分类为树形结构
     * @param $items
     * @return array
     */
    private function getCateTree($items)
    {
        $tree = []; //初始化格式化好的树
        foreach ($items as $k => $item) {
            $items[$k] = ['id' => $item['id'], 'parentid' => $item['parentid'], 'name' => $item['name']];
        }
        foreach ($items as $item) {

            if (isset($items[$item['parentid']])) {
                $items[$item['parentid']]['children'][] = &$items[$item['id']];
            } else {
                $tree[] = &$items[$item['id']];
            }
        }
        return $tree;
    }
}

